<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 搜索和操作栏 -->
    <div class="mb-1 flex justify-between items-center">
      <div>
        <a-button class="flex items-center" @click="router.push('/system/basicSettings')">
          <template #icon>
            <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                d="M11 15l-3-3m0 0l3-3m-3 3h8M3 12a9 9 0 1118 0 9 9 0 01-18 0z" />
            </svg>
          </template>
          返回
        </a-button>
      </div>
      <div class="flex items-center space-x-2 flex-wrap gap-y-1">
        <a-select v-model:value="filters.products" mode="multiple" placeholder="产品" :options="productOptions"
          class="w-40" />
        <a-input v-model:value="filters.featureName" placeholder="特性名称" class="w-40" />
        <a-input v-model:value="filters.level" placeholder="层级" class="w-40" />
        <a-input v-model:value="filters.responsibleGroup" placeholder="责任组" class="w-40" />
        <a-input v-model:value="filters.responsiblePerson" placeholder="责任人" class="w-40" />
        <a-button type="primary" @click="handleSearch" class="flex items-center">
          <template #icon>
            <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
            </svg>
          </template>
          查询
        </a-button>
        <a-button @click="handleReset" class="flex items-center">
          <template #icon>
            <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
            </svg>
          </template>
          重置
        </a-button>
        <a-button type="primary" class="flex items-center" @click="showAddDialog">
          <template #icon>
            <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
            </svg>
          </template>
          添加特性
        </a-button>
      </div>
    </div>

    <!-- 特性列表表格 -->
    <a-table :columns="columns" :data-source="filteredData" :pagination="pagination" @change="handleTableChange"
      class="bg-white rounded-lg shadow-sm">
      <!-- 操作列 -->
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <div class="space-x-4">
            <a-tooltip title="编辑特性">
              <a-button type="link" size="small" @click="handleEdit(record)">
                <template #icon>
                  <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                      d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                  </svg>
                </template>
              </a-button>
            </a-tooltip>
            <a-tooltip title="删除特性">
              <a-button type="link" size="small" danger @click="handleDelete(record)">
                <template #icon>
                  <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                      d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                  </svg>
                </template>
              </a-button>
            </a-tooltip>
          </div>
        </template>
      </template>
    </a-table>
    <AddFeatureDialog ref="addFeatureDialogRef" @refresh="handleRefresh" />
    <EditFeatureDialog ref="editFeatureDialogRef" @refresh="handleRefresh" />
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { getFeatureList, deleteFeature } from '@/utils/api';
import AddFeatureDialog from './AddFeatureDialog.vue';
import EditFeatureDialog from './EditFeatureDialog.vue';
import { Modal, message } from 'ant-design-vue';
import $loading from '@/utils/loading';

const router = useRouter();

// 表格列定义
const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
  },
  {
    title: '产品类型',
    dataIndex: 'productId',
    key: 'productId',
  },
  {
    title: '特性名称',
    dataIndex: 'moduleName',
    key: 'moduleName',
  },
  {
    title: '所属目录',
    dataIndex: 'parentName',
    key: 'parentName',
  },
  {
    title: '层级',
    dataIndex: 'level',
    key: 'level',
  },
  {
    title: '责任组',
    dataIndex: 'groupResponsible',
    key: 'groupResponsible',
  },
  {
    title: '责任人',
    dataIndex: 'personResponsible',
    key: 'personResponsible',
  },
  {
    title: '操作',
    key: 'action',
    width: 120,
  },
];

// 数据列表
const data = ref([]);

// 分页配置
const pagination = ref({
  total: 0,
  current: 1,
  pageSize: 10,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '30', '50'],
  showTotal: (total) => `共 ${total} 条记录`
});

// 筛选条件
const filters = ref<{
  products: number[];
  featureName: string | undefined;
  level: string | undefined;
  responsibleGroup: string | undefined;
  responsiblePerson: string | undefined;
}>({  
  products: [],
  featureName: '',
  level: '',
  responsibleGroup: '',
  responsiblePerson: ''
});

import { productTypeMapping } from '@/utils/productTypeMapping';

// 下拉框选项
const productOptions = Object.entries(productTypeMapping).map(([value, label]) => ({
  value: Number(value),
  label
}));

const levelOptions = [
  { value: 'L1', label: 'L1' },
  { value: 'L2', label: 'L2' },
  { value: 'L3', label: 'L3' },
];

// 筛选后的数据
const filteredData = ref(data);

// 加载数据
const loadData = async () => {
  try {
    const res = await getFeatureList({
      pageNum: pagination.value.current,
      pageSize: pagination.value.pageSize,
      moduleName: filters.value.featureName || undefined,
      personResponsible: filters.value.responsiblePerson || undefined,
      level: filters.value.level || undefined,
      groupResponsible: filters.value.responsibleGroup || undefined
    });
    // 添加序号字段并转换产品ID为产品名称
    data.value = res.records.map((item, index) => ({
      ...item,
      index: (pagination.value.current - 1) * pagination.value.pageSize + index + 1,
      productId: productTypeMapping[item.productId] || item.productId // 使用映射转换产品ID
    }));
    pagination.value.total = res.total;
  } catch (error) {
    console.error('加载特性列表失败:', error);
  }
};

// 搜索处理函数
const handleSearch = () => {
  pagination.value.current = 1;
  loadData();
};

// 重置处理函数
const handleReset = () => {
  filters.value = {
    products: [],
    featureName: undefined,
    level: undefined,
    responsibleGroup: undefined,
    responsiblePerson: undefined
  };
  pagination.value.current = 1;
  loadData();
};

// 表格变化处理函数
const handleTableChange = (pag: any) => {
  pagination.value.current = pag.current;
  pagination.value.pageSize = pag.pageSize;
  loadData();
};

// 初始化加载数据
onMounted(() => {
  loadData();
});

// 编辑特性对话框引用
const editFeatureDialogRef = ref();

// 编辑特性处理函数
const handleEdit = (record: any) => {
  editFeatureDialogRef.value.showModal(record);
};

// 删除特性处理函数
const handleDelete = (record: any) => {
  console.log('删除特性:', record);
  Modal.confirm({
    title: '确认删除该特性？',
    content: `确定删除名为 ${record.moduleName} 的特性吗？`,
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      const loadingInstance = $loading.show();
      try {
        await deleteFeature({
          featureId: record.featureId,
          Isdelete: 1,
        });
        message.success('删除特性成功');
        handleRefresh();
      } catch (error) {
        message.error('删除特性失败');
      } finally {
        loadingInstance.close();
      }
    }
  });
};

// 新增特性对话框引用
const addFeatureDialogRef = ref();

// 显示新增对话框
const showAddDialog = () => {
  addFeatureDialogRef.value.showModal();
};

// 刷新列表
const handleRefresh = () => {
  loadData();
};
</script>

<style scoped>
:deep(.ant-input) {
  text-align: left;
}

:deep(.ant-select-selection-placeholder),
:deep(.ant-select-selection-item) {
  text-align: left;
}
</style>